// 分割文件为多个小块
function sliceFile(file, chunkSize) {
    const chunks = [];
    let start = 0;
    while (start < file.size) {
        const end = Math.min(start + chunkSize, file.size);
        const chunk = file.slice(start, end);
        chunks.push(chunk);
        start = end;
    }
    return chunks;
}

// 上传文件的某个小块
function uploadChunk(url, chunk, onProgress) {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open('POST', url);
        xhr.setRequestHeader('Content-Type', 'application/octet-stream');
        xhr.onload = () => {
            if (xhr.status >= 200 && xhr.status < 300) {
                resolve();
            } else {
                reject(xhr.statusText);
            }
        };
        xhr.onerror = () => reject(xhr.statusText);
        xhr.upload.onprogress = onProgress;
        xhr.send(chunk);
    });
}

// 上传整个文件
async function uploadFile(url, file, chunkSize, onProgress) {
    const chunks = sliceFile(file, chunkSize);
    const totalChunks = chunks.length;
    let uploadedChunks = 0;
    for (let i = 0; i < chunks.length; i++) {
        const chunk = chunks[i];
        try {
            await uploadChunk(url, chunk, (event) => {
                const progress = (uploadedChunks + event.loaded / event.total) / totalChunks;
                onProgress(progress);
            });
            uploadedChunks++;
        } catch (error) {
            console.error(error);
        }
    }
}

// 断点续传
async function resumeUpload(url, file, chunkSize, onProgress, uploadedChunks) {
    const chunks = sliceFile(file, chunkSize);
    const totalChunks = chunks.length;
    for (let i = uploadedChunks; i < chunks.length; i++) {
        const chunk = chunks[i];
        try {
            await uploadChunk(url, chunk, (event) => {
                const progress = (i + event.loaded / event.total) / totalChunks;
                onProgress(progress);
            });
            uploadedChunks++;
        } catch (error) {
            console.error(error);
            break;
        }
    }
    if (uploadedChunks === totalChunks) {
        // 所有块上传完成，合并文件
        // ...
    }
}

// 示例代码
const input = document.querySelector('input[type="file"]');
input.addEventListener('change', () => {
    const file = input.files[0];
    const url = '/upload';
    const chunkSize = 1024 * 1024; // 每个块的大小为1MB
    let uploadedChunks = 0;
    let progress = 0;
    if (localStorage.getItem('uploadedChunks')) {
        uploadedChunks = parseInt(localStorage.getItem('uploadedChunks'), 10);
        progress = uploadedChunks / Math.ceil(file.size / chunkSize);
    }
})
// 只需要把需要上传的文件给你，然后具体的上传逻辑你来做，上传过程返回上传进度
